<?php


class Model_rozvrh extends CI_Model {
	
	public function get_den($n) {
		$dni = array("Po","Ut","St","Št","Pi");
		return $dni[$n];
	} 
	
	public function StrToMins($s) {
		$tm = strtotime($s);
		return (idate("i",$tm)+ 60 * idate("H",$tm));
	}
	
	public function MinsToStr($m) {
		$hr = (string)(($m < 600)?'0'.(int)($m / 60):(int)($m / 60));
		$mn = (string)((($m % 60) < 10)?'0'.($m % 60):($m % 60));
 		return $hr.":".$mn.":00";
	}

	public function get_nonoverlap_rows($res) {
		//$res = ordered mysql result for each day
		$rows = array();
		foreach ($res as $row) {
			$rows[] = $row;
		}
		$res_arr = array();
		$counter = 0;
		while (count($rows) > 0) {
			$res_arr[$counter] = array();
			$last = 0;
			$res_arr[$counter][$last] = array_shift($rows);
			
			foreach ($rows as $r) {
				if (($this->StrToMins($r->cas_od)) >= ($this->StrToMins($res_arr[$counter][$last]->cas_do))) {
					if(($key = array_search($r, $rows)) !== false) {
						$last++;
						unset($rows[$key]);				
						$res_arr[$counter][$last] = $r;
					}
				}
			}
		
			$counter++;
		}
		return $res_arr;
	}
	
	public function get_nazov($id) {
		$this->db->select('nazov')
				 ->from('udalost')
				 ->where('id',$id);
		$query = $this->db->get();
		foreach($query->result() as $r) {
			return $r->nazov;
		}
		return "Error";
	}
	
	public function get_daily_rows($den, $uid = null) {
		$rows = array();
		if ($uid == null) {
			$this->db->select('*')
						->from('casy_udalosti')
						->where('den',$den)
						->order_by('cas_od','asc');
			$query = $this->db->get();
			foreach($query->result() as $row) {
				$rows[] = $row;
			}
			return $rows;
		}
		$this->db->select('*')
			 ->from('kolektiv')
			 ->where('id_uzivatela',$uid);
		$query = $this->db->get();
		$kolektivy = array();
		foreach($query->result() as $row) {
			$kolektivy[] = $row->id;
		}
		if (count($kolektivy) == 0) {
			return $rows;
		}
		$this->db->select('*')
			 ->from('rozvrh')
			 ->where_in('id_kolektiv',$kolektivy);
		$query = $this->db->get();
		$map = $query->result();
		$udalosti = array();
		
		foreach($map as $row) {
			$udalosti[] = $row->id_cas_udalosti;
		}
		if (count($udalosti) == 0) {
			return $rows;
		}
		$this->db->select('*')
				->from('casy_udalosti')
				->where_in('id',$udalosti)
				->where('den',$den)
				->order_by('cas_od','asc');
		$query = $this->db->get();
		foreach($query->result() as $row) {
			$rows[] = $row;
		}
		$result = array();
		foreach($rows as $r) {
			foreach($map as $m) {
				if ($r->id == $m->id_cas_udalosti) {
					$obj = array('kolektiv' => $m->id_kolektiv);
					$result[] = (object) array_merge((array)$r, (array)$obj);
					
				}
			}
		}
		return $result;
	}
	
	
	
	public function test_accuracy($row){
		if ($row->fixna == 0) {
				return ($this->StrToMins($row->cas_od)%30 == 0) &&
					(($row->trvanie + 10)%30 == 0);
		} 
		
		return ($this->StrToMins($row->cas_od)%30 == 0) &&
			(($row->trvanie+10) % 30 == 0); 
	}
	
	private function get_kolektiv_name($id) {
		$this->db->select('trieda')
				 ->from('kolektiv')
				 ->where('id', $id);
		$query = $this->db->get();
		foreach ($query->result() as $res) {
			return $res->trieda;
		}
		return "Nedefinovana trieda";
	}
	
	private function parent_zameranie($pid) {//vrati zameranie z id udalosti
		$this->db->select('id_zameranie')
				->where('id', $pid);
        $udalost = $this->db->get('udalost');
        if ($udalost) {
             $row = $udalost->row();
             return $row->id_zameranie;
        }  
        return 3;
	}
	private function fill_table($nonoverlap, $den, $kolektiv) {
		$od = 7;
		$po = 15;
		$result = "";
		$first = True;
		foreach ($nonoverlap as $line) {
			if (!$first) {
				$result .= "<tr> \n";
			}
			$cas = $od*2; //30 minutove intervaly
			$first = False;
			foreach($line as $row) {
				$gap = (int)($this->StrToMins($row->cas_od)/30) - $cas;
				if ($gap > 0) {
					for ($j = 0; $j < $gap; $j++) {
						$result .= '<td class="'.(($den % 2 == 1)?'odd_':"").'invis" ></td>';
					}
				}
				$trvanie_min = ($row->trvanie+10);
				if ($row->fixna == 0) {
					$pocitacia = $this->StrToMins($row->cas_od);
					$cas_do = $this->StrToMins($row->cas_do);
					
					while ($pocitacia+$trvanie_min <= $cas_do) {
						$result .= '<td ';
						$result .= ' class="zam'.($this->parent_zameranie($row->id_udalosti)).'" ';
						$colspan = $pocitacia % 30 + (int)($trvanie_min/30);
						if ($colspan > 1) {
							$result .= 'colspan="'.$colspan .'" ';
						}
						
						if (!$this->test_accuracy($row)) {
							$result .= ' class="inacc"';
						}
						$result .= '><a href="'.base_url().'udalost/zobraz/'.($row->id).'/'.$pocitacia.'">';
						
						$result .= $this->MinsToStr($pocitacia).'<br /> '.($this->get_nazov($row->id_udalosti));
						$result .= "</a></td> \n";
						$pocitacia += $trvanie_min;
						
					} 
					$cas = (int)($cas_do/30);
					if ($pocitacia<$cas_do) { // ak je rozvrh posunuty
						$cas--;
					}
				} else { 
					$result .= '<td ';
					$result .= ' class="zam'.($this->parent_zameranie($row->id_udalosti)).'" ';
					if (!$this->test_accuracy($row)) {
						$result .= ' class="inacc" ';
					}
					$result .= 'colspan="'.((int)($trvanie_min)/30).'"><a href="'.base_url().
						'udalost/zobraz/'.($row->id).'">';
					if ($kolektiv) {
						$result .= "<strong>".($this->get_kolektiv_name($row->kolektiv))."</strong> \n";
					}
					$result .= $row->cas_od.'<br /> '.($this->get_nazov($row->id_udalosti))."</a></td>\n";
					
					$cas += $gap+(int)($trvanie_min/30);
				}
			}
			$gap = $po*2 - $cas + 2;
			while ($gap > 0) {
				$result .= '<td '.' class="'.(($den % 2 == 1)?'odd_':"").'invis" ></td>'."\n";
				$gap--;
			} 
			$result .= "</tr> \n";
			
		}
		return $result;
	}
	
	public function get_table() {
		$od = 7;
		$po = 15;		
		$result = '<p><a href="'.base_url().'rozvrh/zoznam">zoznam</a></p>';
		$result .= '<table border = 1>';	
		$result .= "<thead><tr><th></th>\n";
		for ($i = $od; $i <= $po; $i++) {
			$result .= "<th>$i:00</th>\n";	
			$result .= "<th>$i:30</th> \n";
			
		}
		$result .= "</tr></thead>\n";
		$result .= "<tbody> \n";
		for ($den = 0; $den < 5; $den++) {
			$result .= "<tr> \n";
			$rows = $this->get_daily_rows($den);
			$nonoverlap = $this->get_nonoverlap_rows($rows);
			if (count($nonoverlap) ==0) {
				$result .= '<th>'.$this->get_den($den)."</th> \n";
				for ($i = 2*$od; $i < 2*($po+1); $i++) {
					$result .= '<td class="'.(($den % 2 == 1)?'odd_':"").'invis"></th>'."\n";	
				}
				$result .= "</tr>\n";
			} else {
				$result .= '<th rowspan = "'.count($nonoverlap).'">'.$this->get_den($den)."</th> \n";
			}
			$result .= $this->fill_table($nonoverlap, $den, false);
			
		}
		$result .= '</table>';
		return $result;
	}
	
	public function moj_rozvrh($uid) {
		$od = 7;
		$po = 15;		
		$result = '<p><a href="'.base_url().'rozvrh/myzoznam">zoznam</a></p>';
		$result .= '<table border = 1>';	
		$result .= "<thead><tr><th></th>\n";
		for ($i = $od; $i <= $po; $i++) {
			$result .= "<th>$i:00</th>\n";	
			$result .= "<th>$i:30</th> \n";
			
		}
		$result .= "</tr></thead>\n";
		$result .= "<tbody> \n";
		for ($den = 0; $den < 5; $den++) {
			$result .="<tr> \n";
			$rows = $this->get_daily_rows($den, $uid);
			$nonoverlap = $this->get_nonoverlap_rows($rows);
			if (count($nonoverlap) ==0) {
				$result .= '<th>'.$this->get_den($den)."</th> \n";
				for ($i = 2*$od; $i < 2*($po+1); $i++) {
					$result .= '<td class="'.(($den % 2 == 1)?'odd_':"").'invis"></th>'."\n";	
				}
				$result .= "</tr>\n";
			} else {
				$result .= '<th rowspan = "'.count($nonoverlap).'">'.$this->get_den($den)."</th> \n";
			}
			$result .= $this->fill_table($nonoverlap, $den, true);
			
		}
		$result .= '</table>';
		return $result;
	}
	
	private function get_zameranie($n) {
		$arr = array('Matematika','Fyzika','Informatika', 'Iné');
		return $arr[$n];
	}
	
	
	private function get_ucitel($id) {
		$this->db->select('ucitel')
				->from('udalost')
				->where('id', $id);
        $ud = $this->db->get();
		if ($ud) {
             $row = $ud->row();
             return $row->ucitel;
        }  
        return "Neznamy";
	}
	
	//vseobecny zoznam, moznost filtrovat
	public function get_vypis_list($zameranie = null, $ucitelId = null) {
		$result = '';
		$result .= '<p><strong><a href="'.base_url().'rozvrh">Tabuľka</a></strong></p>';
		
		$result .= '<h3>Filter zameraní:</h3><ul>';
		for ($i = 0; $i < 4; $i++) {
			$result .= '<li><a href="'.base_url().'rozvrh/zoznam/'.$i.'">'.$this->get_zameranie($i).'</a></li>';
		}
		$result .= "</ul> \n";
		
		$ucitel = null;
		
		if ($ucitelId != null) {
			$ucitel = $this->get_ucitel($ucitelId); 
		}
		if($zameranie != null && $ucitelId != null) {
			return '<strong>Chyba! </strong><a href="'.base_url().'rozvrh/zoznam">Späť na rozvrh</a>';
		}
		if($zameranie != null || $ucitelId != null) {
			$result .= "<h2>Výpis podľa ".(($zameranie==null)?"uciteľa (".$ucitel.")":'zamerania ');
			if ($zameranie != null) {
				$result .= $this->get_zameranie($zameranie);
			}
			$result .=":</h2> \n";
			$result .= '<a href="'.base_url().'rozvrh/zoznam">Nefiltrovaný výpis</a></strong>'."\n";
			
		} else {
			$result .= "<h2>Výpis:</h2>";
		}
		
		
		$this->db->select('*')
				 ->from('udalost');
		
		if ($zameranie != null) {
			$this->db->where('id_zameranie',$zameranie);
		}
		if ($ucitelId != null) {
			$this->db->where('ucitel',$ucitel);
		} 
		$query = $this->db->get();
	    foreach ($query->result() as $row) {
			$result .= '<p><strong>'. $row->nazov.'</strong>'.' <a href="'.base_url().'rozvrh/zoznam/null/'.$row->id.'"><em>'.$row->ucitel.'</em></a>'."<br />\n";
			
			$this->db->select('*')
					 ->from('casy_udalosti')
			     	 ->where('id_udalosti',$row->id)
			     	 ->order_by('den','acs')
				     ->order_by('cas_od','asc');
			$query2 = $this->db->get();
			foreach ($query2->result() as $row2) {
				if ($row2->fixna == 0) {
					$trvanie_min = ($row2->trvanie+10);
					$pocitacia = $this->StrToMins($row2->cas_od);
					$cas_do = $this->StrToMins($row2->cas_do);
					$result .= $this->get_den($row2->den).':<br />';
					while ($pocitacia+$trvanie_min <= $cas_do) {
						$result .= '<small><a href="'.base_url().'udalost/zobraz/'.($row2->id).'/'.$pocitacia.'">';
						$result .= $this->MinsToStr($pocitacia)." - ".
								$this->MinsToStr($pocitacia+$trvanie_min)."</a></small><br />\n";
						$pocitacia += $trvanie_min;
					}
				} else {
					$result .= $this->get_den($row2->den).': <small><a href="'.base_url().
							'udalost/zobraz/'.($row2->id).'"'.">$row2->cas_od - "
							.$row2->cas_do."</a></small>".'<br />'."\n";
				}
			} 
			$result .= '</p>';
		} 
		return $result;
	}
	
	public function get_vypis_mojlist($uid) {
		$result = '<p><a href="'.base_url().'rozvrh/user_rozvrh">Tabulka</a></p>';
		$result .= "<h2>Vypis:</h2>";
		$this->db->select('id')
				->where('id_uzivatela', $uid)
				->from('kolektiv');
		$query = $this->db->get();
		foreach ($query->result() as $row) {
			$result .= "<p> \n";
			$result .= "<strong>".$this->get_kolektiv_name($row->id).":</strong><br /> \n";
			
			$this->db->select('id_cas_udalosti')
					->from('rozvrh')
					->where('id_kolektiv',$row->id);
			$query2 = $this->db->get();
			$udalosti = array();
			foreach($query2->result() as $row2) {
				$udalosti[] = $row2->id_cas_udalosti;
			}
			if (count($udalosti) == 0) {
				continue;
			}
			$this->db->select('*')
					->from('casy_udalosti')
					->where_in('id',$udalosti)
					->order_by('den','acs')
				    ->order_by('cas_od','asc');
			
			$query2 = $this->db->get();
			foreach($query2->result() as $row2) {
				if ($row2->fixna == 0) {
					$trvanie_min = ($row2->trvanie+10);
					$pocitacia = $this->StrToMins($row2->cas_od);
					$cas_do = $this->StrToMins($row2->cas_do);
					$result .= $this->get_den($row2->den).':<br />';
					while ($pocitacia+$trvanie_min <= $cas_do) {
						$result .= '<small><a href="'.base_url().'udalost/zobraz/'.($row2->id).'/'.$pocitacia.'">';
						$result .= $this->MinsToStr($pocitacia)." - ".
								$this->MinsToStr($pocitacia+$trvanie_min)."</a></small><br />\n";
						$pocitacia += $trvanie_min;
					}
				} else {
					$result .= $this->get_den($row2->den).': <small><a href="'.base_url().
							'udalost/zobraz/'.($row2->id).'"'.">$row2->cas_od - "
							.$row2->cas_do."</a></small>".'<br />'."\n";
				}
			}
			
			$result .="</p> \n";
		}
		
		return $result;
	}
  
  
  
  
  public function get_id_udalosti($key){
        $this->db->where('id', $key);
        $user = $this->db->get('casy_udalosti');
        if ($user) {
             $row = $user->row();
             $data = array(
                  'id' => $row->id_udalosti
             );
             return $data;
        }  
        return NULL;
  }
  
  public function get_info_udalosti($key){
        $this->db->where('id', $key['id']);
        $user = $this->db->get('udalost');
        if ($user) {
             $row = $user->row();
             $udalost = array(
                  'zameranie' => $row->id_zameranie,
                  'miestnost' => $row->miestnost,
                  'ucitel' => $row->ucitel,
                  'nazov' => $row->nazov,
                  'abstrakt' => $row->abstrakt,
                  'maxLudi' => $row->maxludi,
                  'poznamka' => $row->poznamka,
                  'maxprednasok' => $row->maxprednasok,
                  'id_ud' => $row->id
             );
             return $udalost;
        }  
        return NULL;
    }  
    
	
}
?>
